import RequestManager from "../../request/request-manager";
import api from "../../config/api";

const PKG_NAME = 'AUTHENTICATION';
const RESET_FORM = `${PKG_NAME}/RESET_FORM`;
const REQUEST_LOADING = `${PKG_NAME}/REQUEST_LOADING`;
const LOGIN_FAILED = `${PKG_NAME}/LOGIN_FAILED`;
const LOGIN_SUCCESS = `${PKG_NAME}/LOGIN_SUCCESS`;

const resetForm = () => {
    return {
        type: RESET_FORM
    }
};

const requestLoading = () => {
    return {
        type: REQUEST_LOADING
    }
};

const performLogin = (username, password) => {
    return async (dispatch) => {
        dispatch(requestLoading());

        const body = JSON.stringify({
            username: username,
            password: password,
        });

        const response = await RequestManager.post(api.login).body(body).execute();

        if (response.code === 200) {
            dispatch(loginSuccess());
        } else {
            dispatch(loginFailed());
        }
    }
};

const loginSuccess = () => {
    return {
        type: LOGIN_SUCCESS,
    }
};

const loginFailed = () => {
    return {
        type: LOGIN_FAILED,
        error: '11111',
    }
};

export {
    RESET_FORM,
    REQUEST_LOADING,
    LOGIN_SUCCESS,
    LOGIN_FAILED,
    resetForm,
    performLogin,
}